package cn.netty.example3;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class EchoClient {

    private NioEventLoopGroup reuqestGroup;
    private Bootstrap bootstrap;

    private void init(){
        this.reuqestGroup = new NioEventLoopGroup();
        this.bootstrap = new Bootstrap();
        this.bootstrap.channel(NioSocketChannel.class)
                .group(reuqestGroup)
                .option(ChannelOption.TCP_NODELAY,true);
    }


    public EchoClient(){
        init();
    }

    public ChannelFuture doRequest(String host,int port) throws InterruptedException {

        this.bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel ch) throws Exception {

                ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
                ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter));
                ch.pipeline().addLast(new StringDecoder());
                ch.pipeline().addLast(new EchoClientHandle());
            }
        });

        return this.bootstrap.connect(host,port).sync();
    }

    public void release(){
        this.reuqestGroup.shutdownGracefully();
    }

    public static void main(String[] args) {
        EchoClient client = new EchoClient();
        ChannelFuture future = null;
        try {
            future = client.doRequest("127.0.0.1", 8888);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
        }finally {
            client.release();
        }
    }
}
